import socket,select

ss = socket.socket()
ss.bind(("127.0.0.2", 1024))
ss.listen(12)

class Server:
    def __init__(self):
        self.read_list = []
        self.write_list = []
        self.r_list = []
        self.w_list = []
        self.read_list.append(ss)
        self.msg_dict = dict()

    def conmunication(self):
        while True:
            rlist, wlist, xlist = select.select(self.read_list, self.write_list, [])
            for i in rlist:
                if i is ss:
                    try:
                        conn, addr = i.accept()
                        print(addr)
                        self.identify_confirm(conn)
                        self.r_list.append(conn)
                    except Exception:
                        i.close()
                        self.read_list.remove(i)

                else:
                    try:
                        data = i.recv(1024)
                        print(data.decode('utf-8'))
                        if not data:
                            i.close()
                            self.read_list.remove(i)
                            continue
                        self.msg_dict[i] = data.decode('utf-8')
                        self.write_list.append(i)
                        self.read_list.remove(i)
                    except Exception:
                        i.close()
                        self.read_list.remove(i)

            for i in wlist:
                try:
                    i.send("你好".encode('utf-8'))
                    self.read_list.append(i)
                except Exception:
                    i.close()
                finally:
                    self.write_list.remove(i)


    def identify_confirm(self,conn):
        pass_w = conn.recv(1024)
        if pass_w.decode('utf-8') == "天王盖地虎，小鸡炖蘑菇":
            self.read_list.append(conn)
            conn.send("欢迎加入群聊".encode('utf-8'))
        else:
            conn.send("暗号不对".encode('utf-8'))
            conn.close()







if __name__ == "__main__":
    s = Server()
    s.conmunication()




